package cn.edu.ldk.controller;

import cn.edu.ldk.common.CommonJsonResult;
import cn.edu.ldk.pojo.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

import static javax.naming.Context.PROVIDER_URL;

@RestController
public class AddressController {
//    public static final String PROVIDER_URL="http://localhost:8082/provider/";
    public static final String PROVIDER_URL="http://CLOUD-PROVIDER-SERVICE/provider/";

    //注入RestTemplate对象
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/consumer/getAll")
    public List<Address> getAllAddressInfos(){
        List<Address> list = restTemplate.
                getForObject(PROVIDER_URL + "getAddressInfo", List.class);
        //getForObject(参数1，访问提供者服务的url 访问路径
        // 参数2，提交给提供者的参数  没有则不写
        // 参数3，调用完提供者之后返回的数据类型)
        return list;
    }

    //消费者的添加
    @PostMapping("/consumer/save")
    public CommonJsonResult<Void> save(Address address){
        //传对象，是由restTemplate的底层HttpClient把address对象转成Json格式传输给8081消费者的
        CommonJsonResult jsonResult = restTemplate.postForObject(PROVIDER_URL + "save", address, CommonJsonResult.class);
        return jsonResult;
    }

    //根据id查询数据
    @GetMapping("/consumer/getAddinfosById/{id}")
    public CommonJsonResult<Address> getAddinfosById(@PathVariable("id") Integer id){
        CommonJsonResult commonJsonResult
                = restTemplate.getForObject(PROVIDER_URL + "getAddressinfoByid/" + id, CommonJsonResult.class);
            return commonJsonResult;
    }
}
